package cn.innosmart.aq.customize;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

import cn.innosmart.aq.R;

/**
 * Created by David on 2015/7/16.
 */
public class CaptchasView extends ImageView {
    //字符集
    private  final char[] CHARS = {
            '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',
            'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    };
    //设置默认的宽和高
    private int DEFAULT_WIDTH = 100, DEFAULT_HEIGHT = 40;
    //设置验证码的长度
    private int mCodeLength = 4;
    //设置验证码字体大小
    private int mCodeSize=25;
    //设备Background背景
    private Bitmap mBackBitmap;
    //随机对象
    private Random random;
    //随机字符串
    private String code;
    public String getCode() {
        return code;
    }
    //横向文字Padding
    private int baseHorizontalPadding=5;
    private int rangeHorizontalPadding=5;
    private int horizontalPadding=baseHorizontalPadding+rangeHorizontalPadding;
    private int padding_left;
    //竖向文字Padding
    private int baseVerticalPadding=5;
    private int rangeVerticalPadding=5;
    private int verticalPadding=baseVerticalPadding+rangeVerticalPadding;
    private int padding_top;
    //控件g高度
    private int mHeight;
    //控件宽度
    private int mWidth;
    public CaptchasView(Context context) {
        this(context, null);
    }

    public CaptchasView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CaptchasView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CaptchasView, defStyleAttr, 0);
        int n = a.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i);
            switch (attr) {
                case R.styleable.CaptchasView_length:
                    mCodeLength = a.getInt(attr, 4);
                    break;
                case R.styleable.CaptchasView_codeSize:
                    mCodeSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
            }
        }
        a.recycle();
        /**
         * 获得绘制文本的宽和高
         */
        mPaint = new Paint();
        mPaint.setTextSize(mCodeSize);
        mBound = new Rect();
        createCode();
        mPaint.getTextBounds(code, 0, code.length(), mBound);

        /**
         * 初始化随机对象
         */
        random=new Random();
        /**
         * 获得绘制的背景
         */
        BitmapDrawable  mBackDrawble=(BitmapDrawable)this.getBackground();
        if(mBackDrawble!=null){
            mBackBitmap=mBackDrawble.getBitmap();
        }

        this.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                createCode();
                padding_top=0;
                padding_left=0;
                postInvalidate();
            }

        });
    }

    private Paint mPaint;
    private Rect mBound;
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            mWidth = widthSize;
        } else {
            mPaint.setTextSize(mCodeSize);
            mPaint.getTextBounds(code, 0, code.length(), mBound);
            float textWidth = mBound.width();
            int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight()+horizontalPadding*(mCodeLength+1));
            int backWidth=mBackBitmap.getWidth();
            if(desired>backWidth){
                mWidth=desired;
            }else{
                mWidth=backWidth;
                //设置字体Size
            }
        }
        if (heightMode == MeasureSpec.EXACTLY) {
            mHeight = heightSize;
        } else {
            mPaint.setTextSize(mCodeSize);
            mPaint.getTextBounds(code, 0, code.length(), mBound);
            float textHeight = mBound.height();
            int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom()+verticalPadding*2);
            int backHeight=mBackBitmap.getHeight();
            if(desired>backHeight){
                mHeight=desired;
            }else{
                mHeight=backHeight;
                //设置字体Size
            }
        }
        setMeasuredDimension(mWidth, mHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < code.length(); i++) {
            randomTextStyle(mPaint);
            randomPadding();
            canvas.drawText(code.charAt(i) + "", padding_left+mBound.width()/mCodeLength*i, padding_top, mPaint);
        }
    }
    private void randomTextStyle(Paint paint) {
        int color = randomColor();
        paint.setColor(color);
        paint.setFakeBoldText(random.nextBoolean());  //trueΪ���壬falseΪ�Ǵ���
        float skewX = random.nextInt(11) / 10;
        skewX = random.nextBoolean() ? skewX : -skewX;
        paint.setTextSkewX(skewX); //float���Ͳ�����������ʾ��б��������б
    }

    private void randomPadding() {
        padding_left = baseHorizontalPadding + random.nextInt(rangeHorizontalPadding);
        padding_top = baseVerticalPadding + random.nextInt(rangeVerticalPadding)+mBound.height();
    }

    private  String createCode() {
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < mCodeLength; i++) {
            buffer.append(CHARS[new Random().nextInt(CHARS.length)]);
        }
        code=buffer.toString();
        return code;
    }

    private int randomColor() {
        return randomColor(1);
    }

    private int randomColor(int rate) {
        int red = random.nextInt(256) / rate;
        int green = random.nextInt(256) / rate;
        int blue = random.nextInt(256) / rate;
        return Color.rgb(red, green, blue);
    }

    public String newCode(){
        createCode();
        padding_left=0;
        padding_top=0;
        postInvalidate();
        return  code;
    }

    private void drawLine(Canvas canvas, Paint paint) {
        int color = randomColor();
        int startX = random.nextInt(mWidth);
        int startY = random.nextInt(mHeight);
        int stopX = random.nextInt(mWidth);
        int stopY = random.nextInt(mHeight);
        paint.setStrokeWidth(1);
        paint.setColor(color);
        canvas.drawLine(startX, startY, stopX, stopY, paint);
    }


}
